package com.jiang.mall.mallmember.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jiang.common.to.LoginTo;
import com.jiang.common.to.SocialUser;
import com.jiang.common.utils.HttpUtils;
import com.jiang.common.utils.PageUtils;
import com.jiang.common.utils.Query;
import com.jiang.mall.mallmember.dao.MemberDao;
import com.jiang.mall.mallmember.dao.MemberLevelDao;
import com.jiang.mall.mallmember.entity.MemberEntity;
import com.jiang.mall.mallmember.entity.MemberLevelEntity;
import com.jiang.mall.mallmember.exception.PhoneException;
import com.jiang.mall.mallmember.exception.UsernameException;
import com.jiang.mall.mallmember.service.MemberService;
import com.jiang.mall.mallmember.vo.MemberUserRegisterVo;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;


@Service("memberService")
public class MemberServiceImpl extends ServiceImpl<MemberDao, MemberEntity> implements MemberService {

    @Autowired
    MemberLevelDao memberLevelDao;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<MemberEntity> page = this.page(
                new Query<MemberEntity>().getPage(params),
                new QueryWrapper<MemberEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void regist(MemberUserRegisterVo memberUserRegisterVo) {
        MemberEntity memberEntity = new MemberEntity();

        //设置默认等级
        MemberLevelEntity memberLevelEntity = memberLevelDao.getDefaultLevel();
        memberEntity.setLevelId(memberLevelEntity.getId());

        //设置用户名 手机号，要求唯一
        memberEntity.setUsername(memberUserRegisterVo.getUserName());
        memberEntity.setMobile(memberUserRegisterVo.getPhone());
        memberEntity.setNickname(memberUserRegisterVo.getUserName());

        //设置密码
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        String encode = bCryptPasswordEncoder.encode(memberUserRegisterVo.getPassword());
        memberEntity.setPassword(encode);

        //其它默认信息

        baseMapper.insert(memberEntity);
    }

    //alt+insert 等同于 myeclipse 的 source
    @Override
    public void checkPhoneUnique(String phone) throws PhoneException {
        Integer count = baseMapper.selectCount(new QueryWrapper<MemberEntity>().eq("mobile", phone));
        if(count > 0) {
            throw new PhoneException();
        }
    }

    @Override
    public void checkUsernameUnique(String username) throws UsernameException {
        Integer count = baseMapper.selectCount(new QueryWrapper<MemberEntity>().eq("username", username));
        if(count > 0) {
            throw new UsernameException();
        }
    }

    @Override
    public MemberEntity login(LoginTo loginTo) {
        String loginacct = loginTo.getLoginacct();
        String password = loginTo.getPassword();
        MemberEntity memberEntity = baseMapper.selectOne(new QueryWrapper<MemberEntity>().eq("username", loginacct));
        if(memberEntity == null) {
            return null;
        }else {
            BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
            boolean matches = bCryptPasswordEncoder.matches(password, memberEntity.getPassword()); // password: 123456
            if(matches) {
                return memberEntity;
            }else {
                return null;
            }
        }
    }

    @Override
    public MemberEntity login(SocialUser socialUser) {
        // 注册和登录合并逻辑
        String uid = socialUser.getUid();
        MemberEntity memberEntity = this.baseMapper.selectOne(new QueryWrapper<MemberEntity>().eq("social_uid", uid));
        if(memberEntity != null) {
            // 这个用户已注册
            MemberEntity update = new MemberEntity();
            update.setId(memberEntity.getId());
            update.setAccessToken(socialUser.getAccess_token());
            update.setExpiresIn(socialUser.getExpires_in());
            this.baseMapper.updateById(update);

            memberEntity.setAccessToken(socialUser.getAccess_token());
            memberEntity.setExpiresIn(socialUser.getExpires_in());
            return memberEntity;
        }else {
            // 没有查到当前用户的对应的记录就注册一个
            MemberEntity regist = new MemberEntity();
            // 查询当前社交用户的社交信息（昵称，性别）
            try {
                HashMap<String, String> hashMap = new HashMap<>();
                hashMap.put("access_token", socialUser.getAccess_token());
                hashMap.put("uid", socialUser.getUid());
                HttpResponse response = HttpUtils.doGet("https://api.weibo.com", "/2/users/show.json", "get", new HashMap<>(), hashMap);
                if(response.getStatusLine().getStatusCode() == 200) {
                    String json = EntityUtils.toString(response.getEntity());
                    JSONObject jsonObject = JSON.parseObject(json);
                    String name = jsonObject.getString("name");
                    String gender = jsonObject.getString("gender");
                    regist.setNickname(name);
                    regist.setGender("m".equals(gender) ? 1 : 0);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            regist.setSocialUid(socialUser.getUid());
            regist.setAccessToken(socialUser.getAccess_token());
            regist.setExpiresIn(socialUser.getExpires_in());
            this.baseMapper.insert(regist);
            return regist;
        }
    }
}